//
//  SettingViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/10/9.
//

import UIKit

class SettingViewController: BaseViewController {
    var tableView: BaseTableView!
    var appVersion: String = "1.0.0"
    var appCache: String = "0MB"
    var appLanguage: String = ""
    var closeAccountBtn: UIButton!
    var phoneStr = ""
    var indexBaseData: IndexBaseDataModel?
    var autoArray: [BottomArticleCategoryModel] = [] //用来装载联络我们 关于我们 隐私条款 法律声明
//    var userData: UserInfoDataModel?  //个人信息data
    var oldAppLan: String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("setting", comment: "设置")
        self.navBar.wr_setBottomLineHidden(hidden: true)
        
        tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight - TabbarHeight), style: .grouped)
        tableView.register(SettingTableCell.self, forCellReuseIdentifier: "SettingTableCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        view.addSubview(tableView)
        self.createBottomView()
        self.initialData()
        
//        self.fetchGetInfo()
        self.fetchGetIndexBaseDetail()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //缓存
        DispatchQueue.global().async {
            let cache = XTManageCenter.getAllCacheSize()
            DispatchQueue.main.async {
                self.appCache = String(format: "%@M", cache)
                self.tableView.reloadData()
            }
        }
    }
    
    func createBottomView(){
        let bgView = UIView(frame: CGRect(x: 0, y: kScreenHeight - TabbarHeight, width: kScreenWidth, height: TabbarHeight))
        bgView.backgroundColor = .white
        self.view.addSubview(bgView)
        
        self.closeAccountBtn = UIButton(frame: CGRect(x: 14, y: 10, width: kScreenWidth - 28, height: 44))
        self.closeAccountBtn.backgroundColor = .white
        self.closeAccountBtn.addTarget(self, action: #selector(closeAccountBtnAntion), for: .touchUpInside)
        self.closeAccountBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
        self.closeAccountBtn.setup_titleLabel(text: MMLocalizedString("close_account", comment: "注销账号"))
        self.closeAccountBtn.setTitleColor(UIColor(hex: 0x939AA8), for: .normal)
        bgView.addSubview(self.closeAccountBtn)
    }
    
    /**
     case english = "en"
     case chinese_simple = "zh-Hans"
     case chinese_hk = "zh-HK"
     */
    private func initialData(){
        
        //版本
        let infoDict = Bundle.main.infoDictionary
        let version: String = infoDict!["CFBundleShortVersionString"] as! String
        self.appVersion = String(format: "v%@", version)
        
        //语言
        let curLan = XTManageCenter.getAppleLanguages()
        var tempStr = ""
        switch curLan {
            case AppLanguage.english.rawValue:
                //英文
                tempStr = MMLocalizedString("launch_en", comment: "English")
            case AppLanguage.chinese_simple.rawValue:
                //中文
                tempStr = MMLocalizedString("launch_cn", comment: "简体中文")
            default:
                //默认繁体
                tempStr = MMLocalizedString("launch_hk", comment: "繁體中文")
        }
        self.appLanguage = tempStr
        self.oldAppLan = curLan
        self.tableView.reloadData()
    }
    
    ///获取用户信息
//    private func fetchGetInfo(){
//        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.memberGetDetail, objectType: UserInfoResModel.self) { data in
//            let resultObj = data as! UserInfoResModel
//            if resultObj.code == "1" {
//                self.userData = resultObj.data
//            }else{
//                self.view.makeToast(message: resultObj.msg ?? "")
//            }
//        } error: { err in
//            self.view.makeToast(message: err?.domain ?? "")
//
//        }
//    }
        
    ///id是通过indexBaseDetail接口中的bottomArticleCategories
    ///拿到联络我们CONTACTUS的id
    ///拿到id后，再去请求getListVerbose
    private func fetchGetIndexBaseDetail(){
        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.indexBaseDetail, objectType: IndexBaseResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! IndexBaseResModel
            if resultObj.code == "1" {
                var tempArr = resultObj.data?.bottomArticleCategories ?? []
                tempArr = tempArr.filter{$0.code != "45f0d06c-d6a3-466d-8f52-b0e8370d5752"}
                self.autoArray = tempArr
                self.tableView.reloadData()
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    //注销帐号
    @objc func closeAccountBtnAntion(){
        let vc = CancelAccountViewController()
        vc.phoneStr = self.phoneStr
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    ///清除缓存
    @objc func clearCacheAction(){
        XTAlertView.showAlertView(title: "", message: MMLocalizedString("setting_clear_cache", comment: "确认要清除缓存吗?"), cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"), otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")]) { (alert, tag) in
            printLog(tag)
            if(tag == 1) {
                //清除缓存
                XTManageCenter.cleanCache {
                    self.appCache = "0M"
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    ///语言切换
    private func changeLanguage(){
        let vc = LanguagePickerView()
        vc.modalPresentationStyle = .overFullScreen
        vc.callBack = { [weak self] lan in
            self?.fetchGetParam(lan: lan)
        }
        self.present(vc, animated: false)
    }
    
    
    ///重新获取参数
    private func fetchGetParam(lan: String){
        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.baseParameter(param: ["":""]), objectType: BaseParameterModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! BaseParameterModel
            if resultObj.code == "1" && resultObj.data != nil {
                XTManageCenter.setLocalPlaceParameter(paramData: resultObj.data)
                self.appLanguage = lan
                self.view.makeToast(message: MMLocalizedString("change_success", comment: "切换成功"))
                self.perform(#selector(self.handleSuccess), with: nil, afterDelay: 1.2)
            }else{
                self.handleChangeFailed()
                self.view.makeToast(message: resultObj.msg ?? "")
                
            }
        } error: { err in
            self.handleChangeFailed()
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///语言切换成功，修改回原来的值
    @objc func handleSuccess(){
        self.reloadAppLanguage()
    }
    
    ///语言切换失败时，修改回原来的值
    @objc func handleChangeFailed(){
        XTManageCenter.setLocalDataString(aKey: UtilCenter.kAppLanguage, aValue: self.oldAppLan)
        self.tableView.reloadData()
    }
    
    ///刷新语言
    private func reloadAppLanguage(){
        guard let tempTabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let tempIndex = tempTabbarVC.selectedIndex
        let tabbarVC = BaseTabbarController()
        tabbarVC.selectedIndex = tempIndex
        UIApplication.shared.keyWindow?.rootViewController = tabbarVC
        
        guard let navi = tabbarVC.childViewControllers[tempIndex] as? BaseNavigationController else {
            return
        }
        
        let vc = SettingViewController()
        navi.pushViewController(vc, animated: false)
    }
    
    ///检查更新
    private func checkupdateAction() {
        //检查更新
        let url = "https://apps.apple.com/cn/app/kool-car/id1631105769?mt=8"
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(URL.init(string: url)!, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(URL.init(string: url)!)
        }
        
    }
}

extension SettingViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
            case 0:
                return 2 + self.autoArray.count
            case 1:
                return 3
            default:
                return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 10
        }
        return 20
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SettingTableCell", for: indexPath) as! SettingTableCell
        cell.rightTitleLab.text = ""
        switch (indexPath.section, indexPath.row) {
            case (0, 0):
                //我的资料
                cell.titleLab.text = MMLocalizedString("profile_title", comment: "我的资料")
            case (0, 1):
                //更改密码
                cell.titleLab.text = MMLocalizedString("update_password", comment: "更改密码")
            case (0, _):
                let tempIndex = indexPath.row - 2
                if self.autoArray.count > tempIndex {
                    let model = self.autoArray[tempIndex]
                    cell.titleLab.text = model.name ?? ""
                }else{
                    cell.titleLab.text = "11"
                }
            case (1, 0):
                //语言/Language
                cell.titleLab.text = MMLocalizedString("setting_language", comment: "语言/Language")
                cell.rightTitleLab.text = self.appLanguage
            case (1, 1):
                //检查更新
                cell.titleLab.text = MMLocalizedString("setting_check_update", comment: "检查更新")
                cell.rightTitleLab.text = self.appVersion
            case (1, 2):
                //清除缓存
                cell.titleLab.text = MMLocalizedString("setting_clear", comment: "清除缓存")
                cell.rightTitleLab.text = self.appCache
            default:
                ()
        }
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch (indexPath.section, indexPath.row) {
            case (0, 0):
                //我的资料
                let vc = MyUserInfoViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            case (0, 1):
                //更新密码
                let vc = UpdatePwdViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            case (0, _):
                //关于我们 联络我们 法律声名 隐私条款
                guard self.autoArray.count > indexPath.row - 2  else {
                    return
                }
                let itemObj = self.autoArray[indexPath.row - 2]
                let vc = ContactUsViewController()
                vc.titleStr = itemObj.name ?? ""
                vc.contactId = "\(itemObj.id ?? 0)"
                self.navigationController?.pushViewController(vc, animated: true)
            case (1, 0):
                //多语言
                self.changeLanguage()
            case (1, 1):
                //检查更新
                self.checkupdateAction()
            case (1, 2):
                //清除缓存
                self.clearCacheAction()
            default:
                ()
        }
    }
}
